package com.mall.service.mallLogs.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.model.domain.Timeoutlog;
import com.mall.model.dto.MallLogsDto;
import com.mall.service.mallLogs.mapper.MallLogsMapper;
import com.mall.service.mallLogs.mapper.TimeoutlogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 统计接口超时次数
 */
@Service
public class CountTimeoutService {

    @Autowired
    private MallLogsMapper mallLogsMapper;

    @Autowired
    private TimeoutlogMapper timeoutlogMapper;

    public void countTimeout() {
        //定义起始时间
        DateTime yesterday = DateUtil.yesterday();
        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(yesterday);
        DateTime today = DateUtil.date();
        String endTime = new SimpleDateFormat("yyyy-MM-dd").format(today);
        //查询出超时的接口
        List<MallLogsDto> mallLogsDtoList = mallLogsMapper.countTimeout(startTime, endTime);
        for (MallLogsDto mallLogsDto : mallLogsDtoList) {
            //取出数据
            String methodUrl = mallLogsDto.getMethodUrl();
            String method = mallLogsDto.getMethod();
            Integer isTimeout = mallLogsDto.getIsTimeout();
            Integer countTimeout = mallLogsDto.getCountTimeout();
            String startendtime = startTime+"至"+endTime;

            //查询数据库规定时间是否有相同的数据，有就更新，没有就添加
            Timeoutlog timeoutlog = timeoutlogMapper.select(methodUrl, method, startendtime);
            //不存在保存
            if (timeoutlog == null) {
                timeoutlog = new Timeoutlog();
                timeoutlog.setMethodUrl(methodUrl);
                timeoutlog.setMethod(method);
                timeoutlog.setIsTimeout(isTimeout);
                timeoutlog.setCountTimeout(countTimeout);
                timeoutlog.setStartendtime(startendtime);
                timeoutlogMapper.save(timeoutlog);
            }
            //存在更新
            Integer id = timeoutlog.getId();
            timeoutlogMapper.update(countTimeout, id);
        }
    }
}
